#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   forms.py
@Time    :   2021/10/10 20:12:33
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, Regexp, Length
from app.models import User


class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(message='请输入用户名')])
    password = PasswordField('密码', validators=[DataRequired(message='请输入密码')])
    remember_me = BooleanField('记住用户名')
    submit = SubmitField('登录')


# RegistrationForm继承自FlaskForm
class RegistrationForm(FlaskForm):
    # StringField用来获取字符型数据，validators是验证器，Regexp中填写的是正则表达式
    username = StringField('用户名', validators=[DataRequired(message='用户名已注册'), Regexp('^[A-Za-z][A-Za-z0-9_.]*$',
                                                                                     0,'用户名只能包含字母，数字，点'
                                                                                        '或下划线'), Length(1, 64)])
    # Email验证器用来验证输入是否是邮箱格式，但不确保邮箱是否存在
    email = StringField('邮箱', validators=[DataRequired(message='请输入邮箱'), Email(message='邮箱地址已使用')])
    password = PasswordField('密码', validators=[DataRequired(message='请输入密码')])
    password2 = PasswordField('确认密码', validators=[DataRequired(message='请输入确认密码'),
                                                            EqualTo('password',message='密码不一致')])
    submit = SubmitField('注册')
    
    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('请输入不同的用户名')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('请输入不同的邮箱地址')